package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWeChatService;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @create: 严佳保
 * 日期 :2025/10/16 15:29
 * 功能 :
 **/
@Service
public class WeChatServiceImpl implements IWeChatService {

    @Value("${weChat.appId}")
    private String appid;

    @Value("${weChat.appSecret}")
    private String secret;

    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public String getopenid(String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        HttpResponse response = HttpUtil.createRequest(Method.GET, OPENID_URL)
                .form(params)
                .execute();
        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject.getStr("openid");
        }
        return null;

    }

    @Override
    public String getphone(String phoneCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        HttpResponse response = HttpUtil.createRequest(Method.POST, PHONE_URL + gettoken())
                .body(JSONUtil.toJsonStr(params))
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String pohne = jsonObject.getByPath("phone_info.phoneNumber", String.class);

            return pohne;
        }
        return null;
    }
    private String gettoken() {

        System.out.println(appid);
        System.out.println(secret);

        Map<String,Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        params.put("grant_type","client_credential");
        HttpResponse response = HttpUtil.createRequest(Method.GET, TOKEN_URL)
                .form(params)
                .execute();

        if (response.isOk()) {
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject.getStr("access_token");
        }
        return null;

    }
}